package se.plingapp.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import se.plingapp.entitybeans.User;

/**
 *
 *
 * @author erikbrannstrom
 */
public class AuthorizationFilter implements Filter {

    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    /**
     *
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     */
    @Override
    public void doFilter(ServletRequest request,
            ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession httpSession = httpRequest.getSession();
        String servletPath = httpRequest.getServletPath();

        // If we are requesting a resource, skip authorization
        if (servletPath.endsWith(".png")
                || servletPath.endsWith(".jpg")
                || servletPath.endsWith(".gif")
                || servletPath.endsWith(".css.xhtml")
                || servletPath.endsWith(".js.xhtml")) {
            chain.doFilter(request, response);
            return;
        }

        // Retrieve the current user from the session
        User user = (User) httpSession.getAttribute("user");

        // If the user is authenticated, the start page should not be displayed
        if (user != null && servletPath.endsWith("start.xhtml")) {
            httpResponse.sendRedirect("/pling.nbp/user/dashboard.xhtml");
        } // If the user is not authenticated, redirect to start page
        else if (user == null && !servletPath.endsWith("start.xhtml")) {
            httpResponse.sendRedirect("/pling.nbp/start.xhtml");
        } // If the user is authenticated, perform authorization
        else if (user != null && !user.isAdmin() && servletPath.indexOf("admin") > -1) {
            httpResponse.sendError(401);
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }
}
